import {getSearch} from '../../service/goods';

Page({
  data: {
    tabs: [
      {
        id: 0,
        title: '综合',
        isActive: true
      },
      {
        id: 1,
        title: '销量',
        isActive: false
      },
      {
        id: 2,
        title: '价格',
        isActive: false
      }
    ],
    goodsList: [],
    isScrollTop: false
  },
  QueryInfo: {
    query: '',
    cid: '',
    pagenum: 1,
    pagesize: 10
  },
  total: 0,
  onLoad(options) {
    this.pageInit(options);
  },
  // 页面初始化操作
  pageInit: async function(options) {
    this.QueryInfo.cid = options.cid || '';
    // 首页标签点进来时可能会用到
    this.QueryInfo.query = options.query || '';

    let goods_list = await getSearch(this.QueryInfo);
    this.total = goods_list.data.message.total;
    this.setData({
      goodsList: goods_list.data.message.goods
    })
  },
  tabClick(e) {
    let id = e.detail.id;
    let tabs = this.data.tabs;
    tabs.forEach(item => item.isActive = item.id === id ? true : false);

    this.setData({tabs});
  },
  // 添加所加载的数据
  addGoodsList: async function() {
    let new_goods = await getSearch(this.QueryInfo);
    let goodsList = this.data.goodsList;
    goodsList.push(...new_goods.data.message.goods);
    this.setData({goodsList})
  },
  // 上拉加载操作
  handleScrollBottom() {
    let total = this.total;
    let {pagesize, pagenum} = this.QueryInfo;
    if(Math.ceil(total/pagesize) <= pagenum) {
      return wx.showToast({
        title: '已经加载完了呦',
        icon: 'success',
      });
    }
    this.QueryInfo.pagenum += 1;
    this.addGoodsList();
  },
  // 下拉刷新操作
  handleScrollTop: async function() {
    this.QueryInfo.pagenum = 1;
    this.total = 0;
    this.setData({
      goodsList: []
    })

    let new_goods = await getSearch(this.QueryInfo);
    this.total = new_goods.data.message.total;
    this.setData({
      goodsList: new_goods.data.message.goods,
      isScrollTop: false
    })
  }
})